package com.lgl.mes.technology.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lgl.mes.basedata.entity.MaterialExcel;
import com.lgl.mes.basedata.entity.SpMaterile;
import com.lgl.mes.basedata.service.impl.FileNotEmptyException;
import com.lgl.mes.common.util.ExcelUtil;
import com.lgl.mes.common.util.SpringUtil;
import com.lgl.mes.common.util.org.easy.excel.ExcelContext;
import com.lgl.mes.common.util.org.easy.excel.model.StudentModel;
import com.lgl.mes.common.util.org.easy.excel.result.ExcelImportResult;
import com.lgl.mes.technology.entity.BomExcel;
import com.lgl.mes.technology.entity.SpBom;
import com.lgl.mes.technology.mapper.SpBomMapper;
import com.lgl.mes.technology.service.ISpBomService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwenze.poi.ExcelKit;
import com.wuwenze.poi.handler.ExcelReadHandler;
import com.wuwenze.poi.pojo.ExcelErrorField;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  BOM服务实现类
 * </p>
 *
 * @author lgl
 * @since 2020-03-28
 */
@Service
public class SpBomServiceImpl extends ServiceImpl<SpBomMapper, SpBom> implements ISpBomService {

    public List<List<Map<String, Object>> >    LocalImportMap(MultipartFile file) {
        String message = "";

        List<List<Map<String, Object>> > resList = new ArrayList();
        List<String>  headList=  new ArrayList();
        if (file.isEmpty()) {
            throw new FileNotEmptyException("上传文件不能为空");
        }

        try {
            Workbook web = SpringUtil.getBean(ExcelUtil.class).getExcelInfo(file);
            Sheet sheet = web.getSheetAt(0);
            ExcelUtil.totalRows = sheet.getLastRowNum();

            // 获取Excel的列数(前提是有行数)
            if (ExcelUtil.totalRows > 0 && sheet.getRow(0) != null) {
                ExcelUtil.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            }


            Row headRow = sheet.getRow(1);
            for (int col = 0; col < ExcelUtil.totalCells ; col++) {
                headList.add(headRow.getCell(col).getStringCellValue());
            }


            for (int rowIndex = 2; rowIndex < ExcelUtil.totalRows + 1; rowIndex++) {//从第二行开始写,标题在第一行
                boolean str = true;
                Row row = sheet.getRow(rowIndex);
                if (row == null) {
                    continue;
                }

                // 循环Excel的列

                List<Map<String, Object>>  rowList = new ArrayList();

                for (int c = 0; c < ExcelUtil.totalCells; c++) {
                    Cell cell = row.getCell(c);
                    Map<String, Object> map = new HashMap<String, Object>();

                   /* if (cell != null) {
                    }
*/
                    map.put(headList.get(c),cell);
                    rowList.add(map);

                }
                resList.add(rowList);
            }

        }
        catch (Exception e) {
        message = e.getMessage();
        e.printStackTrace();
        return null;
    }


        return  resList;
    }





        @Override
    public String LocalImport(MultipartFile file) {
            String message = "上传完毕";

            if (file.isEmpty()) {
                throw new FileNotEmptyException("上传文件不能为空");
            }

            /*
            List<BomExcel> successList = new ArrayList();
        List<Map<String, Object>> errorList = new ArrayList();

        Workbook web = SpringUtil.getBean(ExcelUtil.class).getExcelInfo(file);
        Sheet sheet = web.getSheetAt(0);
        ExcelUtil.totalRows = sheet.getLastRowNum();
        // 获取Excel的列数(前提是有行数)
        if (ExcelUtil.totalRows > 1 && sheet.getRow(0) != null) {
            ExcelUtil.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        Map<String,List> map = new HashMap<String,List>();
        for (int r = 1; r < ExcelUtil.totalRows+1; r++) {//从第二行开始写,标题在第一行
            boolean str = true;
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            // 循环Excel的列
            for (int c = 0; c < ExcelUtil.totalCells; c++) {
                Cell cell = row.getCell(c);
                if (cell != null) {
                }


            }
        }

*/

        /*
                    try {
            ExcelKit.$Import(BomExcel.class)
                    .readXlsx(file.getInputStream(), new ExcelReadHandler<BomExcel>() {
                        @Override
                        public void onSuccess(int i, int i1, BomExcel bomExcel) {
                            successList.add(bomExcel); // 单行读取成功，加入入库队列。
                        }
                        @Override
                        public void onError(int sheetIndex, int rowIndex, List<ExcelErrorField> list) {
                            // 读取数据失败，记录了当前行所有失败的数据
                            Map<String, Object> map = new HashMap<>();
                            map.put("sheetIndex", sheetIndex);
                            map.put("rowIndex", rowIndex);
                            map.put("errorFields", list);
                            errorList.add(map);
                        }
                    });



        try
        {
            successList.stream().forEach(item ->{
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(item);
                String materielCode  = jsonObject.getString("materielCode");
                String bomCode  = jsonObject.getString("bomCode");
                QueryWrapper<SpBom> wrapper=new QueryWrapper<>();
                wrapper.eq("bom_code", bomCode); //按materiel_code  而不是 bom_code
                wrapper.eq("materiel_code", materielCode);
                if (this.list(wrapper).size()==0) {
                    SpBom spBom = new SpBom(jsonObject);
                    this.baseMapper.insert(spBom);
                }
            });
        } catch (Exception e) {
            message = e.getMessage();
            e.printStackTrace();
        }

         */



            /*  第一种方案又两个问题提 ，顺序对不上，具有随机性，另外就是又的电脑上正常，有的电脑不能正常工作，
            下面是第二种方案， 它的问题是 ，不能很好的处理excel中的 信息，比如那边的文本 444，解析后它自动按数字解析的，并且变成了 444.0
            我操 啊  ~~~~
            所以， 我们只能使用下面的第三种方案， 网上用友很多种方案 ，省事的没有
            ****/

            /****

            try
            {
                List<List<Map<String, Object>> > resList = LocalImportMap(file);
                resList.stream().forEach(item ->{
                    //
                    //List<Map<String, Object>>  list = (List<Map<String, Object>> )item;
                    //JSONObject jsonObject = (JSONObject) JSONObject.toJSON(list);
                    String bomCode   = item.get(0).get("bomCode").toString();
                    String materielCode  = item.get(1).get("materielCode").toString();
                    QueryWrapper<SpBom> wrapper=new QueryWrapper<>();
                    wrapper.eq("bom_code", bomCode); //按materiel_code  而不是 bom_code
                    wrapper.eq("materiel_code", materielCode);
                    if (this.list(wrapper).size()==0) {
                        SpBom spBom = new SpBom();
                        if(item.get(0).get("bomCode")!=null)
                        spBom.setBomCode(item.get(0).get("bomCode").toString());
                        if(item.get(1).get("materielCode")!=null)
                        spBom.setMaterielCode(item.get(1).get("materielCode").toString());
                        if(item.get(2).get("materielDesc")!=null)
                        spBom.setMaterielDesc(item.get(2).get("materielDesc").toString());
                        if(item.get(3).get("factory")!=null)
                        spBom.setFactory(item.get(3).get("factory").toString());

                        this.baseMapper.insert(spBom);
                    }
                });
            } catch (Exception e) {
                message = e.getMessage();
                e.printStackTrace();
            }


             */

            try
            {
                String config = "excel/mes-excel-config.xml";
                // 配置文件路径
                ExcelContext context = new ExcelContext(config);
                // Excel配置文件中配置的id
                String excelId = "bom";

                ExcelImportResult result = context.readExcel(excelId, 0, file.getInputStream());
                List<SpBom>  items = result.getListBean();
                for(SpBom item:items){
                    QueryWrapper<SpBom> wrapper=new QueryWrapper<>();
                    wrapper.eq("bom_code", item.getBomCode());
                    wrapper.eq("materiel_code", item.getMaterielCode());
                    if (this.list(wrapper).size()==0) {
                        this.baseMapper.insert(item);
                    }
                }

            } catch (Exception e) {
                message = e.getMessage();
                e.printStackTrace();
            }

            return message;
    }

    public List<String >   GetBomList()
    {

        return this.baseMapper.getBomList();

    }

}
